package com.fjec.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.BusinessUtil;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.im.entity.BizUserConversation;
import com.fjec.im.mapper.BizUserConversationMapper;
import com.fjec.im.service.IBizUserConversationService;
import com.fjec.im.view.ConversationVO;
import com.fjec.user.feign.MarketClient;
import com.google.common.base.Strings;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 012.用户会话表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-23
 */
@Service
public class BizUserConversationServiceImpl extends ServiceImpl<BizUserConversationMapper, BizUserConversation> implements IBizUserConversationService {

    @Resource
    private BizUserConversationMapper mapper;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Resource
    private MarketClient marketClient;

    @Override
    public JsonResult getConvList(Page page) {
        Long userId = AccountInfo.getUserId();
        Page<Map<String, Object>> resultPage = mapper.getConvList(page, userId);
        List<ConversationVO> resultList = new ArrayList<>();
        for (Map<String, Object> map : resultPage.getRecords()) {
            ConversationVO view = new ConversationVO();
            view.setId(MapUtils.getLong(map, "Id"));
            long userId1 = MapUtils.getLong(map, "UserId1");
            if (userId1 == userId.longValue()) {
                view.setUserId1(MapUtils.getLong(map, "UserId2"));
                view.setUserName1(MapUtils.getString(map, "UserName2"));
                Integer busiType2 = MapUtils.getInteger(map, "BusiType2");
                view.setBusiType1(busiType2);
                view.setBusiTypeName1(BusinessUtil.busiType2Str(busiType2));
                view.setHeadPic1(MapUtils.getString(map, "HeadPic2"));
                view.setIsSelf(1);
            } else {
                view.setUserId1(userId1);
                view.setUserName1(MapUtils.getString(map, "UserName1"));
                Integer busiType1 = MapUtils.getInteger(map, "BusiType1");
                view.setBusiType1(busiType1);
                view.setBusiTypeName1(BusinessUtil.busiType2Str(busiType1));
                view.setHeadPic1(MapUtils.getString(map, "HeadPic1"));
                view.setIsSelf(0);
            }
            Timestamp createTime = (Timestamp) MapUtils.getObject(map, "CreateTime");
            Object lastMsgTime = MapUtils.getObject(map, "MsgTime");
            view.setCreateTime(DateUtil.milli2Ldt(createTime.getTime()));
            view.setLastMsgTime(lastMsgTime == null ? null : String.valueOf(((Timestamp)lastMsgTime).getTime() / 1000));
            view.setLastMessage(MapUtils.getString(map, "Content"));
            view.setUnReadNum(MapUtils.getInteger(map, "Unrc", 0));

            resultList.add(view);
        }
        return JsonResult.success()
                .data(resultList)
                .total(resultPage.getTotal())
                .build();
    }

    @Override
    public JsonResult createOrGetConversation(Long toId, Integer busiType, String shopName) throws Exception {
        Long userId = AccountInfo.getUserId();
        // 查询是否之前有会话
        QueryWrapper<BizUserConversation> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(q -> q.eq("userId1", toId).eq("userId2", userId))
                .or(q -> q.eq("userId1", userId).eq("userId2", toId));
        BizUserConversation entity = mapper.selectOne(queryWrapper);
        ConversationVO view = new ConversationVO();
        if (entity == null) {
            Map<String, Object> infoMap = marketClient.getSessionInfo(toId, busiType);
            Integer seflBusiType = AccountInfo.getBusiType();
            // 没有则创建一个会话
            entity = new BizUserConversation();
            // 发起人保存在userId1里
            Long convId = idGenerator.nextId();
            entity.setId(convId);
            entity.setUserId1(userId);
            entity.setBusiType1(seflBusiType);
            entity.setHeadPic1(AccountInfo.getHeadPic());
            switch (seflBusiType) {
                case 2:// 果农
                case 3:// 分拣
                case 4:// 农资
                case 5:// 包装
                case 6:// 采购
                    entity.setUserName1(AccountInfo.getShopName());
                    break;
                case 1:// 个人
                default:
                    String wxNickName = AccountInfo.getWxNickName();
                    entity.setUserName1(Strings.isNullOrEmpty(wxNickName) ? "" : wxNickName);
                    break;
            }
            // 另外一个人保存在userId2里
            entity.setUserId2(toId);
            entity.setUserName2(shopName);
            entity.setBusiType2(busiType);
            entity.setHeadPic2(MapUtils.getString(infoMap, "HeadPic"));
            entity.setCreateTime(DateUtil.nowLdt());
            mapper.insert(entity);
            entity = mapper.selectById(convId);
        }
        BeanUtils.copyProperties(view, entity);
        if (view.getUserId1() == AccountInfo.getUserId()) {
            view.setIsSelf(1);
        } else {
            view.setIsSelf(0);
        }
        return JsonResult.success()
                .data(view)
                .build();
    }

    @Override
    public JsonResult getConversation(Long id) {
        BizUserConversation entity = mapper.selectById(id);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0008.getCode())
                    .message(EnumSysCode.ERR_0008.getMsg())
                    .build();
        }
        Map<String, Object> user1Map = marketClient.getSessionInfo(entity.getUserId1(), entity.getBusiType1());
        Map<String, Object> user2Map = marketClient.getSessionInfo(entity.getUserId2(), entity.getBusiType2());
        ConversationVO view = new ConversationVO();
        view.setId(entity.getId());
        view.setUserId1(entity.getUserId1());
        view.setUserId2(entity.getUserId2());
        Integer busiType1 = entity.getBusiType1();
        Integer busiType2 = entity.getBusiType2();
        view.setBusiType1(busiType1);
        view.setBusiType2(busiType2);
        view.setBusiTypeName1(BusinessUtil.busiType2Str(busiType1));
        view.setBusiTypeName2(BusinessUtil.busiType2Str(busiType2));
        if (entity.getBusiType1() == 1) {
            view.setUserName1(MapUtils.getString(user1Map, "WxNickName"));
        } else {
            view.setUserName1(MapUtils.getString(user1Map, "ShopName"));
        }
        if (entity.getBusiType2() == 1) {
            view.setUserName2(MapUtils.getString(user2Map, "WxNickName"));
        } else {
            view.setUserName2(MapUtils.getString(user2Map, "ShopName"));
        }
        view.setHeadPic1(MapUtils.getString(user1Map, "HeadPic"));
        view.setHeadPic2(MapUtils.getString(user2Map, "HeadPic"));
        if (view.getUserId1().longValue() == AccountInfo.getUserId().longValue()) {
            view.setIsSelf(1);
        } else {
            view.setIsSelf(0);
        }
        return JsonResult.success()
                .data(view)
                .build();
    }

    @Override
    public JsonResult getAndUpdateConversation(Long id) throws Exception {
        BizUserConversation entity = mapper.selectById(id);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0008.getCode())
                    .message(EnumSysCode.ERR_0008.getMsg())
                    .build();
        }
        Map<String, Object> user1Map = marketClient.getSessionInfoByUserId(entity.getUserId1());
        Map<String, Object> user2Map = marketClient.getSessionInfoByUserId(entity.getUserId2());
        // 更新User1
        Integer tmpInt = MapUtils.getInteger(user1Map, "BusiType");
        String tmpStr;
        if (tmpInt == 1) {
            tmpStr = MapUtils.getString(user1Map, "WxNickName");
        } else {
            tmpStr = MapUtils.getString(user1Map, "ShopName");
        }
        entity.setBusiType1(tmpInt);
        entity.setUserName1(tmpStr);
        entity.setHeadPic1(MapUtils.getString(user1Map, "HeadPic"));
        // 更新User2
        tmpInt = MapUtils.getInteger(user2Map, "BusiType");
        if (tmpInt == 1) {
            tmpStr = MapUtils.getString(user2Map, "WxNickName");
        } else {
            tmpStr = MapUtils.getString(user2Map, "ShopName");
        }
        entity.setBusiType2(tmpInt);
        entity.setUserName2(tmpStr);
        entity.setHeadPic2(MapUtils.getString(user2Map, "HeadPic"));
        mapper.updateById(entity);
        // 设置view
        ConversationVO view = new ConversationVO();
        BeanUtils.copyProperties(view, entity);
        view.setBusiTypeName1(BusinessUtil.busiType2Str(entity.getBusiType1()));
        view.setBusiTypeName2(BusinessUtil.busiType2Str(entity.getBusiType2()));
        if (view.getUserId1().longValue() == AccountInfo.getUserId().longValue()) {
            view.setIsSelf(1);
        } else {
            view.setIsSelf(0);
        }
        return JsonResult.success()
                .data(view)
                .build();
    }
}
